package com.inkegz.message.repo.action

import android.util.Log
import com.inkegz.message.entity.ConversationEntity
import com.inkegz.message.entity.ConversationEntity_
import com.inkegz.message.entity.MessageEntity
import com.inkegz.message.entity.MessageEntity_
import com.inkegz.message.repo.base.ObjectBoxAction
import com.inkegz.message.repo.base.ObjectBoxState
import com.inkegz.message.utils.conversationBox
import com.inkegz.message.utils.messageBox
import io.objectbox.kotlin.inValues

/**
 * 添加 会话 操作
 */
class AddConversationAction(
    private val conversationList: List<ConversationEntity>
) : ObjectBoxAction() {

    override suspend fun opt(state: ObjectBoxState): ObjectBoxState {
        Log.i("ImRepo","addConversationAction conversationList: ${conversationList.map { conversation -> conversation.conversationKey }}")
        val conversationBox = state.conversationBox()
        val messageBox = state.messageBox()
        // 查询本地会话 如果已经存在则合并
        val localConversationIdMap = conversationBox.query()
            .inValues(ConversationEntity_.conversationKey, conversationList.map(ConversationEntity::conversationKey).toTypedArray())
            .build()
            .find()
            .associate { localConversation -> localConversation.conversationKey to localConversation.id }
        conversationList.forEach { conversation ->
            val localId = localConversationIdMap[conversation.conversationKey]
            localId?.also { id -> conversation.id = id }
            val messageIdMap = conversation.messages.associateBy { message -> message.messageId }
            val localMessageList = messageBox.query()
                .inValues(MessageEntity_.messageId, conversation.messages.map(MessageEntity::messageId).toLongArray())
                .build()
                .find()
            localMessageList.forEach { localMessage ->
                messageIdMap[localMessage.messageId]?.also { message ->
                    message.id = localMessage.id
                    messageBox.put(message)
                }
            }
        }
        conversationBox.put(conversationList)
        return ObjectBoxState(state.model)
    }
}